package com.yint.browser;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;

import androidx.annotation.NonNull;

import com.yint.browser.widget.BrowserNavigationView;
import com.yint.browser.widget.CustomViewContainer;

import java.util.regex.Pattern;

/**
 * 浏览器网页展示界面
 */

public class WebViewActivity extends BaseActivity {

    private static final String TAG = "WebViewActivity";

    public static final String KEY_URL = "key_url";

    //匹配网址
    private final String URL_REGEX = "^((https|http|ftp)?://)?(([A-Za-z0-9~]+)\\.)+([A-Za-z0-9~])+(\\/.+\\/)?(\\/.*)?$";
    //不是网址用百度进行搜锁关键词
    private final String URL_FOR_SEARCH = "https://www.baidu.com/s?ie=UTF-8&wd=";

    private Pattern pattern = Pattern.compile(URL_REGEX);

    // 用来显示横屏的布局
    private CustomViewContainer layoutForHorizontalScreen;
    private BrowserWebView browserWebView;
    private BrowserNavigationView navView;

    public static void openWebPageByUrl(Context context, String url) {
        Log.d(TAG, "openWebPageByUrl url:" + url);
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra(KEY_URL, url);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview_layout);
        initView();
        handleExtra();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.d(TAG, "onNewIntent");
        super.onNewIntent(intent);
        setIntent(intent);
        handleExtra();
    }

    private void initView() {
        layoutForHorizontalScreen = findViewById(R.id.layout_for_horizontal_screen);
        browserWebView = findViewById(R.id.browserWebView);
        navView = findViewById(R.id.nav_view);

        browserWebView.setCustomViewExhibitor(customViewExhibitor);
    }

    private void handleExtra() {
        Log.d(TAG, "handleExtra");
        Intent intent = getIntent();
        if (intent == null) {
            Log.d(TAG, "handleExtra intent is null");
            return;
        }
        openWebPage(prepareUrl(intent.getStringExtra(KEY_URL)));
    }

    private synchronized void openWebPage(String url) {
        Log.d(TAG, "openWebPage url:" + url);
        if (TextUtils.isEmpty(url)) {
            return;
        }
        browserWebView.loadUrl(url);
    }

    /**
     * 横竖屏切换监听
     */
    @Override
    public void onConfigurationChanged(@NonNull Configuration config) {
        super.onConfigurationChanged(config);
        switch (config.orientation) {
            case Configuration.ORIENTATION_LANDSCAPE:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                break;
            case Configuration.ORIENTATION_PORTRAIT:
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
                break;
        }
    }

    private String prepareUrl(String keyWord) {
        Log.d(TAG, "prepareUrl keyWord:" + keyWord);
        if (TextUtils.isEmpty(keyWord)) {
            return null;
        }
        if (pattern == null) {
            pattern = Pattern.compile(URL_REGEX);
        }
        String finalUrl = keyWord;
        boolean urlMatched = pattern.matcher(keyWord).matches();
        Log.d(TAG, "prepareUrl urlMatched:" + urlMatched);
        if (urlMatched) {
            int index = keyWord.indexOf("://");
            Log.d(TAG, "prepareUrl indexOf(://) index:" + index);
            if (index == -1) {
                finalUrl = "http://" + finalUrl;
            } else if (index == 0) {
                finalUrl = "http" + finalUrl;
            }
        } else {
            finalUrl = URL_FOR_SEARCH + keyWord;
        }
        Log.d(TAG, "prepareUrl finalUrl:" + finalUrl);
        return finalUrl;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyDown keyCode:" + keyCode);
        if (browserWebView != null) {
            if (keyCode == KeyEvent.KEYCODE_BACK && browserWebView.canGoBack()) { // 表示按返回键时的操作
                browserWebView.goBack(); // 后退
                return true; // 已处理
            } else if (keyCode == KeyEvent.KEYCODE_FORWARD && browserWebView.canGoForward()) {// 表示按前进键时的操作
                browserWebView.goForward();//前进
                return true;// 已处理
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private final BrowserWebView.CustomViewExhibitor customViewExhibitor = new BrowserWebView.CustomViewExhibitor() {
        @Override
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
            Log.d(TAG, "webChromeClient onShowCustomView");
            layoutForHorizontalScreen.setTitle(browserWebView.getPageTitle());
            layoutForHorizontalScreen.showCustomView(view, callback);
            layoutForHorizontalScreen.setVisibility(View.VISIBLE);
            layoutForHorizontalScreen.bringToFront();
            browserWebView.setVisibility(View.GONE);
            //设置横屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @Override
        public void onHideCustomView() {
            Log.d(TAG, "webChromeClient onHideCustomView");
            layoutForHorizontalScreen.hideCustomView();
            layoutForHorizontalScreen.setVisibility(View.GONE);
            browserWebView.setVisibility(View.VISIBLE);
            //设置竖屏
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        browserWebView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        browserWebView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (layoutForHorizontalScreen != null) {
            layoutForHorizontalScreen.clear();
        }
        browserWebView.destroy();
    }

}
